#!/bin/python3

import xml.etree.ElementTree as xml
import sys
import re

def main():
  args = sys.argv
  if len(args) == 1:
    print("mbm.xml -> xml")
    print("Usage:")
    print(sys.argv[0], "<xml file>")
    print("e.g.: ", sys.argv[0], "e085.xml")
    return

  xmlfile = sys.argv[1]
  mbmfile = sys.argv[1].split('.')[0] + '.mbm.xml'
  xmlsrc = xml.ElementTree(file = xmlfile)
  mbmsrc = xml.ElementTree(file = mbmfile)

  xmlitems = xmlsrc.getroot().findall('./')

  for index, item in enumerate(mbmsrc.getroot().findall('./')):
    xmlitem = xmlitems[index]
    xmlid = int(xmlitem.get('id'))
    mbmid = int(item.get('id'))
    if xmlid != mbmid:
      print('Mismatch id: ', xmlid, mbmid)
      print('Quit now!')
      return

    source = item.find('./source').text
    target = xmlitem.find('./target').text
    pattern = '\{[0-9a-fA-F{},]*\}'
    srcMatch = re.findall(pattern, source)
    tgtMatch = re.findall(pattern, target)
    if len(srcMatch) != len(tgtMatch):
      print('Mismatch control sequences at id =', xmlid)
      print('Quit now!')
      return

    newTgt = ''
    if len(srcMatch) == 0:
      newTgt = source
    else:
      for i, p in enumerate(srcMatch):
        p = p.replace('{', '\\{')
        p = p.replace('}', '\\}')
        search = re.search(p, source)
        newTgt += source[0:search.span()[0]]
        newTgt += tgtMatch[i]
        source = source[search.span()[1]:len(source)]

    xmlitem.find('./target').text = newTgt

  xmlsrc.write(xmlfile + '.out', encoding='utf-8')

if __name__ == "__main__":
  main()
